<template>
	<u-popup :show="visible" round="16rpx" mode="bottom" @close="hide">
		<view class="quick-group-popup">
			<view class="quick-group-popup__head">
				<text>{{!model.id?'创建':'编辑'}}{{isGroup?'群组':'小组'}}</text>
				<view class="quick-group-popup__head-close bg-hover" @tap="hide">
					<u-image width="32rpx" height="32rpx"
						src="https://file.casugn.com/storecompcard/static/img/tips／close@2x_1681978220794.png"></u-image>
				</view>
			</view>

			<template v-if="userInfo.id">
				<view class="quick-group-popup__form">
					<u-form ref="uForm" :model="model" :rules="rules" labelWidth="120" labelAlign="left"
						labelPosition="left">
						<u-form-item :label="isGroup?'群名':'组名'" prop="groupName" borderBottom required>
							<u-input v-model="model.groupName" border="none" placeholder="请输入(10字内)" maxlength="10"
								:customStyle="inputCustomStyle"></u-input>
						</u-form-item>
						<u-form-item label="图标" prop="groupIcon" borderBottom required>
							<u-upload name="Wx" :fileList="fileListWx" :maxCount="1" multiple width="96rpx"
								height="96rpx" @afterRead="afterRead" @delete="deletePic">
								<view class="upload-box">
									<u-icon name="plus" color="#C9CDD4" size="48rpx"></u-icon>
								</view>
							</u-upload>
						</u-form-item>
						<u-form-item label="公告" borderBottom v-if="isGroup">

							<textarea class="textarea" v-model="model.groupNotice" style="width: 100%;" auto-height
								placeholder-style="font-size:28rpx;color:#666" placeholder="请输入(30字内)"
								:maxlength="30"></textarea>
						</u-form-item>
						<u-form-item label="简介" borderBottom>
							<textarea class="textarea" v-model="model.groupInfo" style="width: 100%;" auto-height
								placeholder-style="font-size:28rpx;color:#666" placeholder="请输入(30字内)"
								:maxlength="30"></textarea>
						</u-form-item>
					</u-form>
				</view>

				<view class="submit-box">
					<u-button v-if="model.id" color="#276AEE" :loading="loading" throttleTime="500"
						@click="submit">保存</u-button>
					<u-button v-else color="#276AEE" :loading="loading" throttleTime="500" @click="submit">提交</u-button>
				</view>
			</template>

			<view v-else class="empty-box">
				<view class="empty-text">无名片不可创建群组</view>
				<u-button color="#276AEE" throttleTime="500"
					:customStyle="{width:'232rpx', height:'64rpx', marginTop:'16rpx', fontSize:'28rpx'}"
					@click="createCard">去创建名片</u-button>
			</view>
		</view>
	</u-popup>
</template>

<script>
	import {
		mapGetters
	} from 'vuex'
	import baseConfig from '@/config/baseUrl.js'

	export default {
		options: {
			styleIsolation: 'shared', // 解除样式隔离
		},
		props: {
			isGroup: {
				type: Boolean,
				default: true
			}
		},
		data() {
			return {
				inputCustomStyle: {
					padding: '10rpx 0'
				},
				visible: false,
				rules: {
					groupName: [{
						required: true,
						max: 10,
						message: '请输入正确的名称',
						trigger: ['blur', 'change'],
					}],
					groupIcon: [{
						required: true,
						message: '请选择图标',
						trigger: ['blur', 'change'],
					}],
				},
				model: {
					groupName: '',
					groupIcon: '',
					groupNotice: '',
					groupInfo: '',
					parentId: '', // 编辑小组时使用
				},
				fileListWx: [],

				loading: false,
			}
		},
		computed: {
			...mapGetters(['userInfo']),
		},
		watch: {
			fileListWx: {
				handler(nVal, oVal) {
					if ((!nVal || !nVal.length) && (!oVal || !oVal.length)) {
						return
					}
					let tFilter = nVal.filter(item => item.status === 'success')
					this.$set(this.model, 'groupIcon', tFilter.map(item => item.url).join(','))

					if (this.userInfo.id && tFilter.length === nVal.length) {
						this.$refs.uForm.validateField(['groupIcon'])
					}
				},
				deep: true
			}
		},
		methods: {
			add(record) {
				if (!record) {
					this.edit({})
				} else if (typeof record === 'object' && !Array.isArray(record)) {
					this.edit({
						parentId: record.parentId || ''
					})
				} else {
					console.error('新增时传入的参数需要是 对象/undefined/null/空字符串')
				}
			},
			edit(record) {
				console.log(record, '子组件接收到的record');
				this.fileListWx = []
				this.model = JSON.parse(JSON.stringify(record))
				if (record.groupIcon) {
					this.fileListWx = [{
						status: 'success',
						url: record.groupIcon
					}]
				}
				this.visible = true
				for (let key of Object.keys(this.model)) {
					// console.log(key);
					this.$set(this.model, key, this.model[key])
				}
				console.log(this.model, 'this.model');
				if (this.userInfo.id) {
					this.$nextTick(() => {
						this.$refs.uForm.setRules(this.rules)
						this.$refs.uForm.clearValidate(['groupName', 'groupIcon'])
					})
				}
			},
			hide() {
				this.visible = false
			},
			submit() {
				const that = this
				this.loading = true
				this.$refs.uForm.validate().then(async success => {
					let params = {
						...that.model,
						icon: that.userInfo.head, //创建人头像
						name: that.userInfo.name, //创建人用户名-必填
						openId: that.userInfo.openId,
					}

					let res = {}
					if (params.id) {
						res = await this.$api.editQuickGruopListById(params)
					} else {
						res = await that.$api.createQuickGroup(params)
					}
					that.loading = false
					if (res.success) {
						uni.showToast({
							title: '提交成功！',
							icon: 'none'
						});
						that.hide()
						that.$emit('refresh')
					} else {
						uni.showToast({
							title: res.message || '提交失败！',
							icon: 'none'
						});
					}
				}).catch(errors => {
					that.loading = false
				})
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				console.log('新增图片', event);
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: event.name,
						url: result,
						fileName: event.file[0].type + event.file[0].size + '',
						filePath: result,
						openId: this.openId
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: baseConfig.uploadUrl + '/sys/common/upload',
						filePath: url,
						name: 'file',
						success: (res) => {
							let data = JSON.parse(res.data)
							if (data.success) {
								resolve(data.message)
							}
						}
					});
				})
			},
			createCard() {
				uni.navigateTo({
					url: '/pagesCard/createCard/createCard'
				})
				this.hide()
			}
		}
	}
</script>

<style lang="scss" scoped>
	.quick-group-popup {

		.quick-group-popup__head {
			position: relative;
			height: 92rpx;
			font-size: 32rpx;
			font-weight: 600;
			color: #1D2129;
			line-height: 44rpx;

			display: flex;
			justify-content: center;
			align-items: center;

			.quick-group-popup__head-close {
				position: absolute;
				top: 30rpx;
				right: 32rpx;
			}
		}

		::v-deep.quick-group-popup__form {
			padding: 24rpx 32rpx;

			.u-form-item__body__left__content__required {
				position: relative !important;
				left: 0 !important;
				padding-right: 10rpx !important;
			}
		}

		::v-deep.u-upload {

			.u-upload__deletable {
				width: 32rpx !important;
				height: 32rpx !important;

				.uicon-close {
					font-size: 24rpx !important;
					line-height: 24rpx !important;
				}
			}

			.u-upload__success {
				.u-upload__success__icon .uicon-checkmark {
					font-size: 28rpx !important;
					line-height: 32rpx !important;
				}
			}
		}

		.upload-box {
			width: 96rpx;
			height: 96rpx;
			background-color: #F7F8FA;
			border-radius: 4rpx;

			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
		}

		.submit-box {
			padding: 0 32rpx 40rpx;
		}

		.empty-box {
			padding: 40rpx 32rpx;

			.empty-text {
				margin-bottom: 24rpx;
				font-size: 24rpx;
				color: #747B84;
				line-height: 34rpx;
				text-align: center;
			}
		}
	}
</style>
